package mi.payment.ui.print;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import mi.payment.R;
import mi.payment.ui.print.helper.PrintTransaction;
import mi.payment.settings.MerManagerSettings;
import mi.payment.db.SettlementModel;
import mi.payment.db.dao.PaySettlement;
import mi.payment.settings.MerchantSettingsOperation;
import mi.payment.transaction.AutoFinishActivity;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.ThreadPoolManager;
import mi.payment.utils.print.DataPrinterKernel;
import sunmi.sunmiui.title.Title;
import woyou.aidlservice.jiuiv5.ICallback;
import woyou.aidlservice.jiuiv5.IWoyouService;

/**
 * 补打交易汇总
 */
public class MakeTransactionSummaryActivity extends AutoFinishActivity {

    //    private RelativeLayout printBankTicket;
    private LinearLayout layoutItems;

    private DataPrinterKernel dataPrinterKernel;

    private SettlementModel settlementModel;

    private List<PrintTransaction> data;

    private Title headtitle;

    public static void start(Context context) {
        Intent starter = new Intent(context, MakeTransactionSummaryActivity.class);
        context.startActivity(starter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maket_ransaction_summary);

        settlementModel = SettlementModel.getInstance();
        dataPrinterKernel = DataPrinterKernel.INSTANCE();
        dataPrinterKernel.init();
        setTitle();
        initView();
        getData();
    }

    /**
     * 初始化View
     */
    private void initView() {
        MerManagerSettings managerSettings = MerchantSettingsOperation.getInstance().getMerManagerSettings();
        TextView tvMerchantName = (TextView) findViewById(R.id.merchant_name);
        String shopName = " ";
        if (!TextUtils.isEmpty(managerSettings.getMerchantName())) {
            shopName = managerSettings.getMerchantName();
        }
        tvMerchantName.setText(getString(R.string.receipt_3_e) + shopName);

        TextView tvMerchantNumber = (TextView) findViewById(R.id.merchant_number_text);
        tvMerchantNumber.setText(getString(R.string.receipt_4_e) + managerSettings.getMerchantNum());

        TextView tvTerminalNumber = (TextView) findViewById(R.id.merchant_terminal);
        tvTerminalNumber.setText(getString(R.string.receipt_5_e) + managerSettings.getTerminalNum());

        layoutItems = (LinearLayout) this.findViewById(R.id.list);
    }

    /**
     * 设置标题
     */
    private void setTitle() {
        headtitle = (Title) this.findViewById(R.id.title);
        headtitle.setHeadBgColor(Color.parseColor("#FD5A51"));
        headtitle.setImageViewAddDrawable(R.drawable.printer);
        headtitle.setButtonVisibility(false, true, true, true);
        headtitle.setTitleText(getString(R.string.transaction_summary));
        headtitle.setMenuClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                headtitle.setButtonVisibility(true, true, true, true);
                print();
            }
        }, null, null);
    }

    /**
     * 获取数据
     */
    private void getData() {
        ThreadPoolManager.executeInCachePool(new Runnable() {
            @Override
            public void run() {
                List<PrintTransaction> printTransactions = new ArrayList<>();
                String batchNumber = mSystemParamsOperation.getSystemParamsSettings().getBatchNumStart();
                PaySettlement settlement = settlementModel.getPaySettlementByBatchNo(batchNumber);
                PrintTransaction printTransaction1 = new PrintTransaction();//内卡贷记
                PrintTransaction printTransaction2 = new PrintTransaction();//内卡借记
                PrintTransaction printTransaction3 = new PrintTransaction();//外卡借记
                PrintTransaction printTransaction4 = new PrintTransaction();//外卡贷记
                printTransaction1.type = getResources().getString(R.string.debit_card1);
                printTransaction2.type = getResources().getString(R.string.credit_card1);
                printTransaction3.type = getResources().getString(R.string.debit_card);
                printTransaction4.type = getResources().getString(R.string.credit_card);
                if (settlement == null) {
                    printTransaction1.total = 0;
                    printTransaction1.totalAmount = 0;
                    printTransaction2.total = 0;
                    printTransaction2.totalAmount = 0;
                    printTransaction3.total = 0;
                    printTransaction3.totalAmount = 0;
                    printTransaction4.total = 0;
                    printTransaction4.totalAmount = 0;
                } else {
                    printTransaction1.total = settlement.CUPDebitCount;
                    printTransaction1.totalAmount = settlement.CUPDebitTotal;
                    printTransaction2.total = settlement.CUPCreditCount;
                    printTransaction2.totalAmount = settlement.CUPCreditTotal;
                    printTransaction3.total = settlement.OtherDebitCount;
                    printTransaction3.totalAmount = settlement.OtherDebitTotal;
                    printTransaction4.total = settlement.OtherCreditCount;
                    printTransaction4.totalAmount = settlement.OtherCreditTotal;
                }
                printTransactions.add(printTransaction1);
                printTransactions.add(printTransaction2);
                printTransactions.add(printTransaction3);
                printTransactions.add(printTransaction4);
                data = new ArrayList<>();
                data.clear();
                data.addAll(printTransactions);
                fillData(printTransactions);
            }
        });
    }

    /**
     * 填充数据
     *
     * @param printTransactions
     */
    private void fillData(final List<PrintTransaction> printTransactions) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                headtitle.setButtonVisibility(false, false, true, true);
                for (int i = 0; i < printTransactions.size(); i++) {
                    View convertView = View.inflate(MakeTransactionSummaryActivity.this, R.layout.item_summary, null);
                    TextView type = (TextView) convertView.findViewById(R.id.tv_t1);
                    TextView money = (TextView) convertView.findViewById(R.id.tv_t3);
                    TextView num = (TextView) convertView.findViewById(R.id.tv_t2);
                    PrintTransaction item = printTransactions.get(i);

                    type.setText(item.type);
                    num.setText(String.valueOf(item.total));

                    String totalAmount = MoneyUtils.longCent2DoubleMoneyStr(printTransactions.get(i).totalAmount);
                    money.setText(totalAmount);
                    layoutItems.addView(convertView);
                }

            }

        });
    }

    /**
     * 打印
     */
    private void print() {
        IWoyouService printService = dataPrinterKernel.getPrinterService();
        try {
            int printStatus = printService.updatePrinterState();
            if(printStatus == 1){
                headtitle.setButtonVisibility(false, true, true, true);
                dataPrinterKernel.printTransactionSummary(data, mICallBack);
            }else{
                showToast(R.string.printer_error);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
            showToast(R.string.printer_error);
        }

    }

    private ICallback mICallBack = new BasePrintCallback() {
        @Override
        public void onPrintResult(int code, String msg) throws RemoteException {

            if (code == 0) {
                // TODO 打印完成了
            }
        }
    };
}
